<template>
  <div :style="'height:' + height + 'px'" :ref="'echart_' + name"></div>
</template>
<script>
const echarts = require('echarts')
export default {
  name: 'line-stack',
  props: {
    name: {
      type: String,
      default: () => {
        return ''
      },
    },
    data: {
      type: Object,
      default: () => {
        return { categories: [], series: [] }
      },
    },
    height: {
      type: Number,
      default: () => {
        return 300
      },
    },
    extend: {
      type: Object,
      default: () => {
        return {
          title: '', //标题
          legend: true, //是否显示legend
          label: true, //是否显示 label
        }
      },
    },
  },
  mounted() {
    this.$watch('data.categories', () => {
      this.init()
    })
  },
  methods: {
    init() {
      const chartEl = this.$refs['echart_' + this.name]
      const myChart = echarts.init(chartEl)
      const { categories, series } = this.data
      const legend = { right: '4%', data: series.map((item) => item.name) }
      const option = {
        title: {
          text: this.extend.title,
          left: '20px',
        },
        grid: {
          left: '20px',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        xAxis: {
          type: 'category',
          data: categories,
        },
        yAxis: {
          type: 'value',
        },
        series: series.map((item) => ({
          name: item.name,
          type: 'bar',
          itemStyle: {
            normal: {
              label: {
                show: this.extend.label,
                position: 'top',
              },
            },
          },
          data: item.data,
        })),
      }
      if (this.extend.legend) {
        option.legend = legend
      }
      myChart.setOption(option)
    },
  },
}
</script>
